package com.zhny.project.txt.properties.controller;

import com.zhny.common.utils.poi.ExcelUtil;
import com.zhny.framework.aspectj.lang.annotation.Log;
import com.zhny.framework.aspectj.lang.enums.BusinessType;
import com.zhny.framework.web.controller.BaseController;
import com.zhny.framework.web.domain.AjaxResult;
import com.zhny.framework.web.page.TableDataInfo;
import com.zhny.project.txt.dataset.domain.TxtDataset;
import com.zhny.project.txt.dataset.service.ITxtDatasetService;
import com.zhny.project.txt.indexset.domain.TxtIndexset;
import com.zhny.project.txt.indexset.service.ITxtIndexsetService;
import com.zhny.project.txt.properties.service.IPropertiesService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 特征工程Controller
 *
 * @author yanqun
 * @date 2019-12-11
 */
@Controller
@RequestMapping("/txt/properties")
public class PropertiesController extends BaseController
{
    private String prefix = "txt/properties";

    @Autowired
    private IPropertiesService propertiesService;
    @Autowired
    private ITxtIndexsetService txtIndexsetService;
    @Autowired
    private ITxtDatasetService txtDatasetService;

    @RequiresPermissions("txt:properties:view")
    @GetMapping()
    public String properties()
    {
        return prefix + "/properties";
    }

    /**
     * 查询特征工程列表
     */
    @RequiresPermissions("txt:properties:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TxtDataset txtDataset)
    {
        startPage();
        List<TxtDataset> list = propertiesService.selectPropertiesList(txtDataset);
        return getDataTable(list);
    }

    /**
     * 查询特征工程列表
     */
    @PostMapping("/check")
    @ResponseBody
    public TableDataInfo check(TxtIndexset txtIndexset)
    {
        List<TxtIndexset> all = txtIndexsetService.selectTxtIndexsetList(txtIndexset);
        return getDataTable(all);
    }



    /**
     * 导出特征工程列表
     */
    @RequiresPermissions("txt:properties:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TxtDataset txtDataset)
    {
        List<TxtDataset> list = propertiesService.selectPropertiesList(txtDataset);
        ExcelUtil<TxtDataset> util = new ExcelUtil<TxtDataset>(TxtDataset.class);
        return util.exportExcel(list, "properties");
    }

    /**
     * 新增特征工程
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存特征工程
     */
    @RequiresPermissions("txt:properties:add")
    @Log(title = "特征工程", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TxtDataset txtDataset)
    {
        return toAjax(propertiesService.insertProperties(txtDataset));
    }

    /**
     * 修改特征工程
     */
    @GetMapping("/edit/{datasetKey}")
    public String edit(@PathVariable("datasetKey") String datasetKey, ModelMap mmap)
    {
        TxtDataset txtDataset = propertiesService.selectPropertiesById(datasetKey);
        mmap.put("properties", txtDataset);
        return prefix + "/edit";
    }

    /**
     * 修改保存特征工程
     */
    @RequiresPermissions("txt:properties:edit")
    @Log(title = "特征工程", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TxtDataset txtDataset)
    {
        return toAjax(propertiesService.updateProperties(txtDataset));
    }

    /**
     * 删除特征工程
     */
    @RequiresPermissions("txt:properties:remove")
    @Log(title = "特征工程", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(propertiesService.deletePropertiesByIds(ids));
    }


    //TXT下载
    @GetMapping("/properties/{datasetKey}")
    public String detail(@PathVariable("datasetKey") String datasetKey,Model model)
    {
        TxtDataset txtDataset = new TxtDataset();
        txtDataset.setDatasetKey(datasetKey);
        model.addAttribute("txtDataset",txtDataset);
        return prefix + "/download";
    }

    //下载保存  StoreHiveset storeHiveset,
//         @RequiresPermissions("Warehouse:hiveset:edit")
//        @Log(title = "数据仓库管理", businessType = BusinessType.UPDATE)
    @GetMapping("/load/{filed1}/{quality1}/{datasetKey}")
//        @ResponseBody
    public void detailSave(@PathVariable("filed1") String filed1, @PathVariable("quality1") String quality1,
                             @PathVariable("datasetKey") String datasetKey,
                             HttpServletRequest request, HttpServletResponse response)
            throws Exception  {
               List<LinkedHashMap<String, Object>> znHandles = txtIndexsetService.ListMapStringObject(filed1, quality1,datasetKey);
                    int txtDataset = txtDatasetService.seletxtDataset(datasetKey);
                    String complete = "";
                    if (txtDataset>0){
                        if (filed1.equals("null") || quality1.equals("null")){
                            if (!filed1.equals("null")){
                                String filed2 = filed1.substring(4);
                                complete = "eigan_value," +  filed2;
                            }
                            if (!quality1.equals("null")){
                                String quality2 = quality1.substring(4);
                                complete = "eigan_value," +  quality2;
                            }
                        }else {
                            String filed2 = filed1.substring(4);
                            String quality2 = quality1.substring(4);
                            StringBuffer txt = new StringBuffer();
                            txt.append( "eigan_value,");
                            txt.append( filed2 + ",");
                            txt.append( quality2);
                            System.out.print(txt);
                            complete = txt.toString();
                        }

                    }else {
                        if (filed1.equals("null") || quality1.equals("null")){
                            if (!filed1.equals("null")){
                                String filed2 = filed1.substring(4);
                                complete =  filed2;
                            }
                            if (!quality1.equals("null")){
                                String quality2 = quality1.substring(4);
                                complete =  quality2;
                            }
                        }else {
                            String filed2 = filed1.substring(4);
                            String quality2 = quality1.substring(4);
                            StringBuffer txt = new StringBuffer();
                            txt.append( filed2 + ",");
                            txt.append( quality2);
                            System.out.print(txt);
                            complete = txt.toString();
                        }
                    }
                 String[] strArr = (complete.split(","));

                 System.out.print(strArr);
                 FileWriter fos = null;
                try {
                    File file = new File("result.txt");
                    fos = new FileWriter(file);
                    StringBuilder sql = new StringBuilder();

                    for (Map map : znHandles) {
                        StringBuilder builder = new StringBuilder();

                        for (String fieldname : strArr) {
                            String fieldValue = map.get(fieldname).toString();
                            builder.append(fieldValue).append(",");
                        }
                        String   text = builder.substring(0,builder.length() - 1);
                        String tet = text + "\r\n";
                        sql.append(tet);
                    }
                    fos.write(sql.toString());
                    fos.flush();
                    fos.close();

                    response.setContentType("text/plain");
                    response.setCharacterEncoding("UTF-8");
                    response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
                    response.setHeader("Content-Length", String.valueOf(file.length()));

                    int length = 0;
                    byte[] buffer = new byte[1024];

                    FileInputStream fis = new FileInputStream(file);
                    OutputStream os = response.getOutputStream();

                    while (-1 != (length = fis.read(buffer, 0, buffer.length))) {
                        os.write(buffer, 0, length);
                    }

                    os.flush();
                    os.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }

    }


}
